package com.esun.cheetah.view.news;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.news.NewsHeadCommunicater;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.model.news.NewsHeadBean;
import com.esun.cheetah.network.ConnectionChangeReceiver;
import com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListViewNews;
import com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListViewNews.OnPrepareForRefreshListener;
import com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListViewNews.OnRefreshListener;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

public class HuoDAct extends Activity implements OnScrollListener, OnItemClickListener, OnRefreshListener,OnPrepareForRefreshListener {
  private PullToRefreshListViewNews listViewNewsTotal; // 全部新闻记录列表
  private ArrayList<Hashtable<String, String>> alItem; // 列表数据存储
  private ArrayList<View> itemViewList;
  private NewsAdapter adapter;
  private LinearLayout linearFooter; // 列表底部加载布局
  
  
  private RelativeLayout rl;
 // private LinearLayout linearNoMore;
  private LinearLayout linearBottom;
  private LinearLayout pull_to_refresh_ll_head;
  private ProgressDialog progressDialog;
  private Button news_agp_btn_refresh;
 // private LinearLayout news_agp_ll_refresh;	   
  public static Handler handlerNews;
  private NewsHeadCommunicater newsHeadCommunicater;
  private String serverMessage; // 服务器返回信息
  private int refreshORBottom = 2; // state=1刷新 state=2到底部
  private Intent intent;
  private Bundle bundle;
  private LinearLayout linearNoMoreNews;
  private ListView lvNoMorenews;
  private boolean isShow = true;
  private boolean isRunning;// 是否正在通信
  private boolean isFirstLoad = true; // 是否是第一次加载
  private boolean isNoMoreRecord = true; // 是否还有记录
  private boolean isBottomChanged = false;

  private int PAGENO = 1;

  private final int NEWS_VIEW_TAG = 10000;
  private final int NEWS_VIEW_TAG2 = 20000;
  private final int NEWS_VIEW_TAG3 = 30000;

  /** add 调整无记录时提示语 */
  private TextView tvNoNews;
  private String strNoNews = "近期暂无活动,敬请期待！";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_total_act);

    initHandler();
    initUI();

  }

  @Override
  protected void onPause() {
    //alItem.clear();
    // TODO Auto-generated method stub
    super.onPause();
    isShow = false;
    this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
  }

  @Override
  protected void onResume() {
    // TODO Auto-generated method stub
    
    super.onResume();
    isShow = true;
    this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(),
        ConnectionChangeReceiver.getIntentFilter());
    if (UserInfo.getUserInfo().isRebuy()) {
      getParent().finish();
    }
    
    
  }

//  @Override
//  protected void onStop() {
//    super.onStop();
//    alItem.clear();
//  }

  // 初始化
  public void initUI() {

    isRunning = false;

    // progressDialog = ViewerUtil.showProgressDialog(HuoDAct.this,
    // getResources().getString(R.string.loading_text));
    // progressDialog.show();

    listViewNewsTotal = (PullToRefreshListViewNews) findViewById(R.id.newstotalact_listview);
    linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryinfoact_linear_footer, null);
    //linearNoMore = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore, null);
    linearBottom = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_bottom_view, null);
    pull_to_refresh_ll_head= (LinearLayout) LayoutInflater.from(this).inflate(R.layout.pull_to_refresh_header, null);
    linearFooter.setTag(NEWS_VIEW_TAG);
    //linearNoMore.setTag(NEWS_VIEW_TAG2);
    linearBottom.setTag(NEWS_VIEW_TAG3);

    alItem = new ArrayList<Hashtable<String, String>>();
    itemViewList = new ArrayList<View>();
    adapter = new NewsAdapter(HuoDAct.this, alItem, itemViewList);
    listViewNewsTotal.addFooterView(linearFooter);// 增加底部状态条
    listViewNewsTotal.setAdapter(adapter);
    listViewNewsTotal.removeFooterView(linearFooter);
    linearNoMoreNews = (LinearLayout) findViewById(R.id.news_total_linear_noRecord);
    lvNoMorenews = (ListView) findViewById(R.id.newstotalact_listview);
    
//    rl = (RelativeLayout) findViewById(R.id.news_rl);
//    rl.setBackgroundColor(R.drawable.bg_default_content_square);
//    
    
    

    listViewNewsTotal.setOnItemClickListener(this);
    listViewNewsTotal.setOnRefreshListener(this);
    listViewNewsTotal.setOnScrollListener(this);
    listViewNewsTotal.setOnPrepareForRefreshListener(this);
    
    tvNoNews = (TextView) findViewById(R.id.news_total_tv_norecord);
    tvNoNews.setText(strNoNews);

    news_agp_btn_refresh = (Button) getParent().findViewById(R.id.news_agp_btn_refresh);
//    news_agp_ll_refresh = (LinearLayout) getParent().findViewById(R.id.news_agp_ll_refresh);
    
	   news_agp_btn_refresh.setVisibility(View.VISIBLE);
	   //news_agp_ll_refresh.setVisibility(View.VISIBLE);
  }

  // 与服务器通信线程
  public void getNewsThread() {
    newsHeadCommunicater = new NewsHeadCommunicater(handlerNews, "11",1);
    newsHeadCommunicater.startCommunicate();
  }

  // 消息处理
  public void initHandler() {
    handlerNews = new Handler() {
      public void handleMessage(Message msg) {
        super.handleMessage(msg);
        listViewNewsTotal.removeFooterView(linearBottom);

        switch (msg.what) {
          case Config.COMMUNICATER_SUCCESS:

            if (newsHeadCommunicater.getLotteryList().size() == 0) {
              isNoMoreRecord = false;
              itemViewList.clear();
              linearNoMoreNews.setVisibility(View.VISIBLE);
              lvNoMorenews.setVisibility(View.GONE);
              if (PAGENO == 0) {
                itemViewList.clear();
                linearNoMoreNews.setVisibility(View.VISIBLE);
                lvNoMorenews.setVisibility(View.GONE);
              } else {
                //listViewNewsTotal.addFooterView(linearNoMore);
              }
            } else {
              PAGENO++;

              communicateSucceed(newsHeadCommunicater.getLotteryList());

              itemViewList.clear();
              adapter.notifyDataSetChanged();
              if (newsHeadCommunicater.getLotteryList().size() < 10) {
                isNoMoreRecord = false;
                //listViewNewsTotal.addFooterView(linearNoMore);
              }
            }
            lengthAutoAdapter();
            endProcess();
            break;

          case Config.COMMUNICATER_FAIL:

            // 通讯失败
            if (isShow) {
              ViewerUtil.showTipDialog(HuoDAct.this, newsHeadCommunicater.getServerMsg(), false);
            }
            lengthAutoAdapter();
            endProcess();

            break;
          case Config.COMMUNICATER_EXCEPTION:

            if (isShow) {
              // ViewerUtil.showTipDialog(LotteryRecordUndoneAct.this,
              // Language.BUG_DIALOG_WEIJIE, false);
              // listViewLotteryRecordTotal.addFooterView(linearNoMore);
              itemViewList.clear();
              linearNoMoreNews.setVisibility(View.VISIBLE);
              lvNoMorenews.setVisibility(View.GONE);
            }
            lengthAutoAdapter();
            endProcess();

            break;

          case Config.DO_REFRESH:
            EDebug.o(this, "do refresh");
            if (!isRunning) {
              //alItem.clear();
              listViewNewsTotal.prepareForRefresh();
              listViewNewsTotal.onRefresh();
              //progressDialog.show();
            }
            NewsAct.isCanClick = true;

            break;

          default:
            break;
        }
      }
    };
  }

  private void endProcess() {
      Button news_agp_btn_refresh = (Button) getParent().findViewById(R.id.news_agp_btn_refresh);
//      LinearLayout news_agp_ll_refresh = (LinearLayout) getParent().findViewById(R.id.news_agp_ll_refresh);	  
  	   news_agp_btn_refresh.setVisibility(View.VISIBLE);
//  	   news_agp_ll_refresh.setVisibility(View.GONE);     	  
    progressDialog = Constant.bar;

    if (refreshORBottom == 1) {
      listViewNewsTotal.onRefreshComplete();
    } else {
      listViewNewsTotal.removeFooterView(linearFooter);
    }
    if (progressDialog != null) {
      progressDialog.cancel();
    }
    isRunning = false;
  }

  // 通讯成功处理
  public void communicateSucceed(ArrayList<NewsHeadBean> LotteryNews) {

    ArrayList<Hashtable<String, String>> alItemTemp = new ArrayList<Hashtable<String, String>>();

    for (int i = 0; i < LotteryNews.size(); i++) {

      Hashtable<String, String> map = new Hashtable<String, String>();
      // 显示参数
      map.put("bigtitle", LotteryNews.get(i).bigtitle);
      map.put("id", LotteryNews.get(i).id);
      map.put("status", LotteryNews.get(i).status);

      alItemTemp.add(map);
      childCount++;
    }
    if (refreshORBottom == 1) {
      alItem.clear();
    }
    alItem.addAll(alItemTemp);
  }

  // 到底事件
  @Override
  public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    // TODO Auto-generated method stub
    if ((firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0)) {
      if (isNoMoreRecord) {
        if (isFirstLoad) {
          listViewNewsTotal.prepareForRefresh();
          listViewNewsTotal.onRefresh();
          isFirstLoad = false;
        } else {
          if (!isRunning && isBottomChanged) {
            isRunning = true;
            isBottomChanged = false;
            listViewNewsTotal.addFooterView(linearFooter);
            refreshORBottom = 2;
            getNewsThread();
          }
        }
      }
    } else {
      isBottomChanged = true;
    }
  }
  
  @Override
public void onPrepareForRefresh() {
	   news_agp_btn_refresh.setVisibility(View.VISIBLE);
//	   news_agp_ll_refresh.setVisibility(View.VISIBLE);	  
}
  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {
    // TODO Auto-generated method stub

  }
  //将menu键点击事件返回给父activity处理
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
   // TODO Auto-generated method stub
   if (keyCode == KeyEvent.KEYCODE_BACK) {
     Activity parent = getParent();
     if (parent != null) {
       parent.onKeyDown(keyCode, event);
       return true;
     }
   }
   return super.onKeyDown(keyCode, event);
 }

  @Override
  public void onRefresh() {
    // TODO Auto-generated method stub
    if (!isRunning) {
      PAGENO = 1;
      isRunning = true;
      isNoMoreRecord = true;
      refreshORBottom = 1;
      groupCount = 0;
      childCount = 0;
      itemViewList.clear();
      linearNoMoreNews.setVisibility(View.GONE);
      lvNoMorenews.setVisibility(View.VISIBLE);
      if (listViewNewsTotal.getFooterViewsCount() != 0) {
        //listViewNewsTotal.removeFooterView(linearNoMore);
      }
      getNewsThread();
    }
  }

//  @Override
//  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//    adapter.notifyDataSetChanged();
//    if (arg1.getTag() != null
//        && (Integer.parseInt(String.valueOf(arg1.getTag())) == NEWS_VIEW_TAG || Integer.parseInt(String.valueOf(arg1.getTag())) == NEWS_VIEW_TAG2 || Integer.parseInt(String.valueOf(arg1
//            .getTag())) == NEWS_VIEW_TAG3)) {
//      return;
//    } else {
//    startActivity(new Intent(HuoDAct.this,NewsContent.class).putExtra(
//        "url", Config.NEWS_CONTENT + alItem.get(arg2 - 1).get("id")));
//    }
  
//  @Override
//  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//    adapter.notifyDataSetChanged();
//    String id=alItem.get(arg2 - 1).get("id");
//    String status=alItem.get(arg2 - 1).get("status");
//    Intent mIntent = new Intent(HuoDAct.this, HuoDContent.class);
//    mIntent.putExtra("id",id);
//    mIntent.putExtra("status",status);
//    startActivity(mIntent);
  
  
  
  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    adapter.notifyDataSetChanged();
    if (arg1.getTag() != null
        && (Integer.parseInt(String.valueOf(arg1.getTag())) == NEWS_VIEW_TAG || Integer.parseInt(String.valueOf(arg1.getTag())) == NEWS_VIEW_TAG2 || Integer.parseInt(String.valueOf(arg1
            .getTag())) == NEWS_VIEW_TAG3)) {
      return;
    } else {
    String id=alItem.get(arg2 - 1).get("id");
    String status=alItem.get(arg2 - 1).get("status");
    Intent mIntent = new Intent(HuoDAct.this, HuoDContent.class);
    mIntent.putExtra("id",id);
    mIntent.putExtra("status",status);
    startActivity(mIntent);
    
    
    
    }
  
  
  
      
      // 修改字体颜色
      TextView textView = (TextView) arg1.findViewById(R.id.news_table_huod_tv_huodhead);
      if (textView != null) {
        textView.setTextColor(Color.GRAY);
        RecordTV.put(arg2, Color.GRAY);
      }
      ImageView imageView = (ImageView) arg1.findViewById(R.id.news_table_huod_imageview_arrows);
      if (imageView != null) {
        imageView.setBackgroundResource(R.drawable.img_pressed_dot);
        RecordIM.put(arg2, R.drawable.img_pressed_dot);
      }

    }

  Map<Integer, Integer> RecordTV = new HashMap<Integer, Integer>();// 点击后记录字体颜色
  Map<Integer, Integer> RecordIM = new HashMap<Integer, Integer>();// 点击后记录图片

  public class NewsAdapter extends BaseAdapter {
    private LayoutInflater listInflater;

    private ArrayList<Hashtable<String, String>> list = new ArrayList<Hashtable<String, String>>();

    private TextView tvNews;
    private ImageView imNews;
    private ImageView imNew;
    private static final String NEWSHEAD = "bigtitle";
    private static final String STATUS = "status";

    public NewsAdapter(Context context, ArrayList<Hashtable<String, String>> tempList, ArrayList<View> tempViewList) {
      this.listInflater = LayoutInflater.from(context);
      this.list = tempList;
    }

    @Override
    public int getCount() {
      return list.size();
    }

    @Override
    public Object getItem(int position) {
      // TODO Auto-generated method stub
      // return recordListView.get(position);
      return null;
    }

    @Override
    public long getItemId(int position) {
      // TODO Auto-generated method stub
      return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

      convertView = listInflater.inflate(R.layout.news_huodlisttable, null);
      tvNews = (TextView) convertView.findViewById(R.id.news_table_huod_tv_huodhead);

      imNews = (ImageView) convertView.findViewById(R.id.news_table_huod_imageview_arrows);
      imNew = (ImageView) convertView.findViewById(R.id.news_table_new_imageview_arrowss);
      tvNews.setText(list.get(position).get(NEWSHEAD));

      EDebug.o(NewsAdapter.this, "新闻头标签" + list.get(position).get(NEWSHEAD));

      tvNews.setTextColor(Color.BLACK);// 你默认的字体颜色
      if (RecordTV.containsKey(position + 1)) {
        tvNews.setTextColor(Color.GRAY);// 点击后的字体颜色
      }

      imNews.setBackgroundResource(R.drawable.img_default_dot);// 你默认的图片
      if (RecordIM.containsKey(position + 1)) {
        imNews.setBackgroundResource(R.drawable.img_pressed_dot);// 点击后的图片
      }
if (list.get(position).get(STATUS).equals("2")) {
        
        imNew.setImageResource(R.drawable.icon_default_hot_huod);

      } else if (list.get(position).get(STATUS).equals("5")) {
        imNew.setImageResource(R.drawable.icon_default_past);

      }
      return convertView;
    }

  }

  private int groupCount = 0;
  private int childCount = 0;

  private void lengthAutoAdapter() {
    int itemHeight = 30 * groupCount + childCount * (30 + 1);

    // 判断是否需要加入额外item
    if (itemHeight < listViewNewsTotal.getHeight()) {
      LinearLayout linearChild = new LinearLayout(this);
      int bheight = 0;
      //linearChild.setBackgroundColor(Color.WHITE);
      if (listViewNewsTotal.getFooterViewsCount() > 0) {
        bheight = listViewNewsTotal.getHeight() - itemHeight - 30;
      } else {
        bheight = listViewNewsTotal.getHeight() - itemHeight;
      }
      linearBottom.addView(linearChild);
      for (int i = 0; i < linearBottom.getChildCount(); i++) {
        linearBottom.getChildAt(i).getLayoutParams().height = bheight;
        linearBottom.getChildAt(i).getLayoutParams().width = LayoutParams.FILL_PARENT;
      }
      TextView a=new TextView(linearChild.getContext());
      a.setFocusable(true);
      //a.setBackgroundResource(R.drawable.anull_icon);
      linearChild.addView(a);
      linearChild.setVisibility(View.VISIBLE);
      listViewNewsTotal.addFooterView(linearBottom);
    }
  }

  @Override
  public void onClick(View v) {
  }

}
